/*
 *    Copyright (c) 2018-2025, cloud All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: cloud
 */
package com.fuyao.cloud.asset.workItem.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.setting.SettingUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fuyao.cloud.asset.inventory.entity.InventoryTask;
import com.fuyao.cloud.asset.inventory.entity.InventoryTaskAsset;
import com.fuyao.cloud.asset.inventory.enums.InventoryTaskAssetStatusEnum;
import com.fuyao.cloud.asset.inventory.enums.InventoryTaskStatusEnum;
import com.fuyao.cloud.asset.inventory.service.InventoryTaskAssetService;
import com.fuyao.cloud.asset.inventory.service.InventoryTaskService;
import com.fuyao.cloud.asset.workItem.dto.WorkItemAssetSearchDTO;
import com.fuyao.cloud.asset.workItem.entity.WorkItem;
import com.fuyao.cloud.asset.workItem.entity.WorkItemList;
import com.fuyao.cloud.asset.workItem.mapper.WorkItemListMapper;
import com.fuyao.cloud.asset.workItem.service.WorkItemListService;
import com.fuyao.cloud.asset.workItem.service.WorkItemService;
import com.fuyao.cloud.asset.workItem.vo.WorkItemAssetVO;
import com.fuyao.cloud.common.biz.service.FyBaseServiceImpl;
import com.fuyao.cloud.common.security.service.CloudUser;
import com.fuyao.cloud.common.security.util.SecurityUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 工作事项明细
 *
 * @author lyhills
 * @date 2023-09-11 12:03:01
 */
@Slf4j
@AllArgsConstructor
@Service
public class WorkItemListServiceImpl extends FyBaseServiceImpl<WorkItemListMapper, WorkItemList> implements WorkItemListService {


    private final WorkItemService workItemService;
    private final InventoryTaskService inventoryTaskService;
    private final InventoryTaskAssetService inventoryTaskAssetService;

    @Override
    public WorkItemList create() {
        return new WorkItemList();
    }

    @Override
    public IPage<WorkItemAssetVO> getWorkItemAssetPage(Page page, QueryWrapper<WorkItemAssetSearchDTO> queryWrapper, WorkItemAssetSearchDTO example) {
        return this.baseMapper.getWorkItemAssetPage(page,queryWrapper,example);
    }

    @Transactional
    @Override
    public boolean saveOrUpdateBatch(Collection<WorkItemList> workItemList) {
        CloudUser user = SecurityUtils.getUser();

        boolean saveOrUpdateBatch = super.saveOrUpdateBatch(workItemList);
        if(saveOrUpdateBatch && CollUtil.isNotEmpty(workItemList)){
            WorkItemList first = CollUtil.getFirst(workItemList);
            // 查询工作事项的明细信息
            List<WorkItemList> workItemLists = this.list(Wrappers.<WorkItemList>query().lambda().eq(WorkItemList::getParentId, first.getParentId()));
            if(CollUtil.isNotEmpty(workItemLists)){
                // 检查状态都不会待盘点时，标记为完成
                boolean noneMatch = workItemLists.stream().noneMatch(workItemListTemp -> InventoryTaskAssetStatusEnum.TODO_INVENTORY.getCode().equals(workItemListTemp.getStatus()));
                if(noneMatch){
                    this.workItemService.doFinishWorkItem(first.getParentId());
                }

                WorkItem workItem = this.workItemService.getById(first.getParentId());
                InventoryTask inventoryTask = this.inventoryTaskService.getById(workItem.getFormId());

                List<Long> assetIds = workItemLists.stream().map(WorkItemList::getSourceId).collect(Collectors.toList());
                List<InventoryTaskAsset> inventoryTaskAssetList = this.inventoryTaskAssetService.list(Wrappers.<InventoryTaskAsset>query().lambda().eq(InventoryTaskAsset::getInventoryTaskId, workItem.getFormId()).in(InventoryTaskAsset::getAssetId, assetIds));
                Set<InventoryTaskAsset> updateInventoryTaskAsset = new HashSet<>();

                if(CollUtil.isNotEmpty(inventoryTaskAssetList)){
                    workItemLists.forEach(workItemListTemp -> {
                        List<InventoryTaskAsset> taskAssetList = inventoryTaskAssetList.stream().filter(inventoryTaskAsset -> inventoryTaskAsset.getAssetId().equals(workItemListTemp.getSourceId())).collect(Collectors.toList());
                        taskAssetList.forEach(taskAssetListTemp ->{
                            taskAssetListTemp.setStatus(workItemListTemp.getStatus());
                            taskAssetListTemp.setDescription(workItemListTemp.getDescription());
                            updateInventoryTaskAsset.add(taskAssetListTemp);
                        });
                    });
                }
                // 修改资产清单状态和说明
                boolean updateBatch = inventoryTaskAssetService.saveOrUpdateBatch(updateInventoryTaskAsset);
                if(updateBatch){
                    // 校验资产清单是否盘点完成
                    List<InventoryTaskAsset> allInventoryTaskAssetList = this.inventoryTaskAssetService.list(Wrappers.<InventoryTaskAsset>query().lambda().eq(InventoryTaskAsset::getInventoryTaskId, workItem.getFormId()));
                    boolean noneInventoryTaskMatch = allInventoryTaskAssetList.stream().noneMatch(inventoryTaskAsset -> inventoryTaskAsset.getStatus().equals(InventoryTaskAssetStatusEnum.TODO_INVENTORY.getCode()));
                    if(noneInventoryTaskMatch){
                        inventoryTask.setStatus(InventoryTaskStatusEnum.COUNTED.getCode());
                        this.inventoryTaskService.saveOrUpdate(inventoryTask);
                        log.info(StrUtil.format("{0}:{1}完成{2}", LocalDateTime.now(),user.getName(),inventoryTask.getSubject()));
                    }
                }
            }
        }
        return saveOrUpdateBatch;
    }
}
